<template>
  <div class="my-book">
    <NavBar @touchmove.prevent></NavBar>
    <div class="my-book-banner">
      <img v-if="bannerUrl" :src="bannerUrl" alt />
      <div class="my-book-banner-text">
        <h1 v-if="bannerText.h1">{{bannerText.h1}}</h1>
        <h2 v-if="bannerText.h2">{{bannerText.h2}}</h2>
      </div>
    </div>
    <ul class="my-book-list">
      <li
        v-for="(item,index) in bookList"
        :key="index"
        @touchstart="showDeleteButton(item)"
        @touchend="emptyTime"
      >
        <img :src="item.image" alt />
        <h1>{{item.title}}</h1>
      </li>
    </ul>
    <div class="no-more" v-if="noMore">☺ 已经到书箱底了哦！</div>
  </div>
</template>

<script>
import NavBar from "@/components/navBar";
const db = wx.cloud.database();
export default {
  components: {
    NavBar
  },
  data() {
    return {
      Loop: null,
      url: [
        "http://data.youxiu.info/yidianBook/banner_0.jpg",
        "http://data.youxiu.info/yidianBook/banner_1.jpg",
        "http://data.youxiu.info/yidianBook/banner_2.jpg",
        "http://data.youxiu.info/yidianBook/banner_3.jpg",
        "http://data.youxiu.info/yidianBook/banner_4.jpg",
        "http://data.youxiu.info/yidianBook/banner_5.jpg",
        "http://data.youxiu.info/yidianBook/banner_6.jpg",
        "http://data.youxiu.info/yidianBook/banner_7.jpg",
        "http://data.youxiu.info/yidianBook/banner_8.jpg"
      ],
      text: [
        {
          h1: "剑未佩妥，出门已是江湖",
          h2: "痞子蔡"
        },
        {
          h1: "人生自有情痴，此恨不关风与月",
          h2: "— 欧阳修《玉楼春》"
        },
        {
          h1: "我舒展开来又蜷缩回去，我挣脱自身独自置身于伟大的风暴中。",
          h2: "— 里尔克"
        },
        {
          h1:
            "一个人在家看电视并不算寂寞，苍白地坐在话不投机人群之中才真正的凄凉",
          h2: "— 亦舒"
        },
        {
          h1: "儿时仰星光，举手若能摘，于今七尺身，天高不可及",
          h2: "— 杜随《杂诗》"
        },
        {
          h1:
            "未曾青梅，青梅枯萎，芬芳满地；不见竹马，竹马老去，相思万里。从此，我爱上的人都像你。",
          h2: "— 王茂《永远记得你》"
        },
        {
          h1: "无聊是对欲望的欲望，我的孤独认识你的孤独。",
          h2: ""
        },
        {
          h1:
            "让花谢的是风雨，让花开的也是风雨，但没了风雨，花不会开也不会落。",
          h2: "— 超觉寺"
        },
        {
          h1: "是一分一秒的陪伴，累积成我们不可替代的情感。",
          h2: "— 巴克曼《时间的礼物》"
        },
        {
          h1: "今人不见古时月，今月曾经照古人。",
          h2: "— 李白《把酒问月·故人贾淳令予问之》"
        },
        {
          h1: "这世上有只有一种成功，就是能够用自己喜欢的方式度过自己的一生。",
          h2: ""
        },
        {
          h1: "人生一世，草生一春，来如风雨，去似微尘。”是什么意思",
          h2: "— 增广贤文"
        },
        {
          h1: "年轻是资本，但很短暂",
          h2: ""
        }
      ],
      openid: "",
      bannerUrl: "http://data.youxiu.info/yidianBook/banner_0.jpg",
      bannerText: {
        h1: "",
        h2: ""
      },
      bookList: [],
      page: 0,
      noMore: false
    };
  },
  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    // console.log("下拉刷新")
    await this.getBanner();
    await this.getBooks(true);
    await wx.stopPullDownRefresh();
    this.emptyTime();
  },
  /**
   * 上拉加载更多
   */
  onReachBottom() {
    // console.log("上拉到底");
    if (!this.noMore) {
      this.page += 1;
      this.getBooks();
    }
  },
  mounted() {
    this.getBanner();
    this.openid = this.$root.$mp.query.id;
    // console.log(this.openid);
    this.getBooks(true);
  },
  methods: {
    //清空
    emptyTime() {
      clearTimeout(this.Loop); //清空定时器，防止重复注册定时器
    },
    /**
     * 图书长按 删除功能
     */
    showDeleteButton(item) {
      clearTimeout(this.Loop); //再次清空定时器，防止重复注册定时器
      this.Loop = setTimeout(
        function() {
          // console.log("长按");
          wx.vibrateLong({
            success: result => {
              wx.showModal({
                title: "提示",
                content: `您确定移除《${item.title}》图书吗？`,
                success: res => {
                  if (res.confirm) {
                    // console.log("确定删除回调函数");
                    // db
                    //   .collection("yidianBook")
                    //   .doc(item._id)
                    //   .remove({
                    //     success: res => {
                    //       // console.log(res);
                    //       this.bookList = this.bookList.filter(
                    //         v => v._id != item._id
                    //       );
                    //     }
                    //   });
                    wx.cloud.callFunction({
                         name:'removebook',
                         data:{
                           _id:item._id
                         }
                    }).then(response =>{
                      console.log(response)
                      wx.showModal({
                        title: "提示",
                        content: `《${item.title}》移除成功`,
                      })
                      if(response.result._id){
                        this.bookList = this.bookList.filter(
                            v => v._id != item._id
                          );
                      }
                    })
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                }
              });
            }
          });
        }.bind(this),
        1000
      );
    },
    // 获取随机banner图 和 文字
    getBanner() {
      let selUrl = this.url[Math.ceil(Math.random() * this.url.length)];
      let selText = this.text[Math.ceil(Math.random() * this.text.length)];
      if (selUrl) {
        this.bannerUrl = selUrl;
        // console.log(this.bannerUrl);
      }
      if (selText) {
        this.bannerText = selText;
        // console.log(this.bannerText);
      }
    },
    async getBooks(init) {
      if (init) {
        this.page = 0;
        this.noMore = false;
      }
      wx.showLoading({ title: "加载中" });
      // const books = await db
      //   .collection("yidianBook")
      //   .where({
      //     _openid: this.openid
      //   })
      //   .orderBy("time", "desc")
      //   .skip(this.page * 9)
      //   .limit(9)
      //   .get();
      let books =await  wx.cloud.callFunction({
         name:'getmybook',
         data:{
           page:this.page
         }
      })
      books =books.result
      console.log(books);
      if (init) {
        this.bookList = books.data;
      } else {
        this.bookList = [...this.bookList, ...books.data];
      }
      if (books.data.length < 9) {
        this.noMore = true;
      }
      wx.hideLoading();
    }
  }
};
</script>

<style>
.my-book {
  width: 100%;
  min-height: 100vh;
  background: url("http://data.youxiu.info/yidianBook/bg/my-book.jpg") left top
    repeat-y;
  /* padding-bottom: 100px; */
  position: relative;
}
.my-book-banner {
  width: 100%;
  height: auto;
  overflow: hidden;
  box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.4);
  position: relative;
  border-radius: 0 0 8px 8px;
}
.my-book-banner img {
  width: 100%;
  display: block;
}
.my-book-banner-text {
  position: absolute;
  width: 100%;
  left: 0;
  bottom: 0;
  color: #ffffff;
  opacity: 0.9;
  background-color: rgba(0, 0, 0, 0.7);
  padding-top: 12px;
  font-size: 14px;
  /* font-weight: bold; */
}
.my-book-banner-text h1 {
  /* text-align: left; */
  text-align: justify;
  padding: 0 20px 10px 20px;
}
.my-book-banner-text h2 {
  text-align: right;
  padding: 0 20px 12px 0;
}
.my-book-list li {
  float: left;
  width: 33.333333%;
  text-align: center;
  margin: 20px 0 0 0;
}
.my-book-list li img {
  /* display: block; */
  width: 100px;
  height: 135px;
  box-shadow: 0px 3px 8px rgba(0, 0, 0, 0.4);
  border-radius: 4px;
}
.my-book-list li h1 {
  width: 100px;
  font-size: 14px;
  display: inline-block;
  color: #333333;
  line-height: 36px;
  font-weight: bold;
  text-align: center;
  white-space: nowrap; /*规定段落中的文本不进行换行*/
  overflow: hidden; /*内容会被修剪，并且其余内容是不可见的。*/
  text-overflow: ellipsis; /*显示省略号来代表被修剪的文本*/
}
.no-more {
  clear: both;
  font-size: 11px;
  color: #333333;
  line-height: 36px;
  text-align: center;
  padding: 20px 0;
}
</style>